/******************************************************************************
*  Copyright(c) 2021-2023 Sietium
*
*  @file:    cineshader.cpp
*  @brif:    cineshader cpp
*
*  @date:    05/10/2021
*  @Author:  cary.Zhang
*
******************************************************************************/
#include <string>
#include <cstdlib>
#include "vmath.h"
#include "glad/gl-headers.h"

#include "window.h"
#include "node.h"
#include "glslprogram.h"
#include "objectfactory.h"

class Shader: public Node
{
public:
    Shader();
protected:
    bool startup();
    void render(double currentTime, double difTime);
    void shutdown();
protected:
    GLuint vao;
    GLuint vbo;
    GLSLProgram program;
};

Shader::Shader()
{
    nodeName = "Shader";
}

bool Shader::startup()
{
    if (PerfWindow::glVersion < 330) {
        printf("Failed! The GL version is less than 3.3 !\n");
        return false;
    }

    makeScreenVao(vao,vbo);

    return program.build("../media/shaders/cineshader/render.vs.glsl",
                         "../media/shaders/cineshader/render.fs.glsl");
}

void Shader::render(double currentTime, double difTime)
{
    (void)difTime;

    glDisable(GL_BLEND);

    static const GLfloat gray[] = {0.0f, 0.8f, 0.2f, 0.0f};
    glClearBufferfv(GL_COLOR, 0, gray);

    program.use();

    program.setUniform1f("uTime", currentTime);

    vmath::vec2 size = vmath::vec2(getWidth(), getHeight());
    program.setUniform2fv("texSize", 1, size);

    glBindVertexArray(vao);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    glDisable(GL_BLEND);
}

void Shader::shutdown()
{
    if (glIsVertexArray(vao))
        glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1,&vbo);
    program.clear();
    glUseProgram(0);
    glBindVertexArray(0);
}

REGISTER_OBJECT(Node, Shader)
